import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';
import { NextFunction } from 'express-serve-static-core';
import { createProxyMiddleware } from 'http-proxy-middleware';

@Injectable()
export class ProxyMiddleware implements NestMiddleware {
  private readonly proxy = createProxyMiddleware({
    target: 'http://127.0.0.1:8888', // 目标服务的地址
    changeOrigin: true, // 修改来源
    onError: (e) => {
      console.log('error', e);
    },
    pathRewrite: (path, req) => {
   '/api':'/'
    },
  });

  use(req: Request, res: Response, next: NextFunction) {
    if (req.originalUrl.startsWith('/api')) {
      // 对于以 "/api" 开头的请求进行转发
      this.proxy(req, res, next);
    } else {
      // 非 API 请求直接调用 next()，不进行转发
      next();
    }
    // this.proxy(req, res, next);
  }
}
